// import { createStore, combineReducers, applyMiddleware } from "redux"
import { createStore, applyMiddleware } from "redux"
import languageReducer from "./reducers/languageReducer"
import recommendProductsReducer from "./recommendProducts/recommendProductsReducer"
import thunk from "redux-thunk"
import { actionLog } from "./middleware/actionLog"
import { productDetailSlice } from "./productDetail/slice"
import { productSearchSlice } from "./productSearch/slice"
import { userSlice } from "./user/slice"
import { combineReducers, configureStore } from "@reduxjs/toolkit"
import { persistStore, persistReducer } from "redux-persist"
import storage from "redux-persist/lib/storage"
import { FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from "redux-persist/es/constants"

// 第一步: 创建配置
const persistConfig = {
	key: "root",
	storage,
	whitelist: ["language", "user"], // 表示只保存 rootReducer 中user的数据
}

const rootReducer = combineReducers({
	language: languageReducer,
	recommendProducts: recommendProductsReducer,
	productDetail: productDetailSlice.reducer,
	productSearch: productSearchSlice.reducer,
	user: userSlice.reducer,
})

// 第二步: 创建persistReducer
const persistReducerInstance = persistReducer(persistConfig, rootReducer)

// const store = createStore(rootReducer, applyMiddleware(thunk, actionLog))
const store = configureStore({
	reducer: persistReducerInstance,
	middleware: getDefaultMiddleware => [
		...getDefaultMiddleware({
			serializableCheck: {
				ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
			},
		}),
		thunk,
		actionLog,
	],
	devTools: true,
})

// 第三步: 创建 persistStore
const persistStoreInstance = persistStore(store)

export type RootState = ReturnType<typeof store.getState>

// export default store
// 第四步: 搭配出persistStore
const out = { store, persistStoreInstance }
export default out
